package snow.endpoint.controller;

import snow.endpoint.entity.MemStatus;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author : liqun
 * @createTime : 2022/2/22 15:42
 */
@Component
public class MemCollector {
    public List<MemStatus> status;
    private int maxSize = 5;
    public MemCollector(List<MemStatus> status) {
        this.status = status;
    }

    @Scheduled(cron = "*/10 * * * * ?") //定时任务
    public void collect() {
        //获取运行时runtime实例，与当前运行环境进行交互
        Runtime runtime = Runtime.getRuntime();
        //获取jvm计划使用最大内存
        Long maxMemory = runtime.maxMemory();
        //返回JVM的内存总量
        Long totalMemory = runtime.totalMemory();
        Map<String, Object> memoryMap = new HashMap<String, Object>(2, 1);
        //获取当前时间并转换成Date类型
        Date date = Calendar.getInstance().getTime();
        //将查到的内存数据存入Map
        memoryMap.put("maxMemory", maxMemory);
        memoryMap.put("totalMemory", totalMemory);
        //如果status的大小超过设定的最大值，将最开始的键值对移除，并将最新的值加入末尾
        if (status.size() > maxSize) {
            status.remove(0);
            status.add(new MemStatus(date, memoryMap));
        } else {
            status.add(new MemStatus(date, memoryMap));
        }
    }
}
